package xin.fsqr520.project.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xin.fsqr520.project.domain.po.Friendship;
import xin.fsqr520.project.domain.po.User;
import xin.fsqr520.project.domain.po.WsChatMessage;
import xin.fsqr520.project.domain.vo.FansVO;
import xin.fsqr520.project.domain.vo.FriendShipVO;
import xin.fsqr520.project.domain.vo.Result;
import xin.fsqr520.project.mapper.FriendshipMapper;
import xin.fsqr520.project.mapper.UserMapper;
import xin.fsqr520.project.mapper.WschatMessageMapper;
import xin.fsqr520.project.service.IFriendShipService;
import xin.fsqr520.project.service.impl.UserServiceImpl;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;


/**
 * 用户控制器，处理用户相关的HTTP请求
 */
@RestController
@RequestMapping("/friend")
public class FriendShipController {

    private static final Logger log = LoggerFactory.getLogger(FriendShipController.class);
    @Autowired
    private FriendshipMapper friendshipMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WschatMessageMapper wschatMessageMapper;

    @Autowired
    private IFriendShipService friendShipService;

    /**
     * 获取userId用户的粉丝列表
     *
     * @param
     * @return
     * @throws Exception
     */
    @GetMapping("/fansList")
    public Result getFansList(Integer userid) throws Exception {
        //先查询当前用户的所有粉丝id列表
        LambdaQueryWrapper<Friendship> wrapper = new LambdaQueryWrapper<Friendship>()
                .eq(Friendship::getFriendId, userid)
                .select(Friendship::getUserId);
        // 2. 使用 selectObjs 查询，直接返回 userId 列表（Object类型，需强转）
        List<Object> fansIdobjs = friendshipMapper.selectObjs(wrapper);

        // 3. 转换为 Integer 列表（避免类型转换异常）
        List<Integer> ids = fansIdobjs.stream()
                .map(obj -> (Integer) obj) // 强转 Integer
                .toList();

        log.info("查出来的粉丝id ：{}", ids);

        List<FansVO> list = new ArrayList<>(ids.size());

        //查询好友的基本信息
        for (int id : ids) {
            //先在user表中查name和avatar
            User u = userMapper.selectById(id);
            if (u == null) return Result.success("查询出错");
            FansVO fansVO = new FansVO();
            BeanUtil.copyProperties(u, fansVO);
            fansVO.setFollowed(followed(userid, id));
            list.add(fansVO);
        }

        return Result.success(list);
    }

    /**
     * 判断请求用户是否关注了这位粉丝
     *
     * @return
     */
    private boolean followed(Integer userId, Integer fansId) {
        LambdaQueryWrapper<Friendship> wrapper = new LambdaQueryWrapper<Friendship>()
                .eq(Friendship::getUserId, userId)
                .eq(Friendship::getFriendId, fansId);
        return friendShipService.count(wrapper) == 1;
    }

    /**
     * 获取userId用户的关注列表
     *
     * @param
     * @return
     * @throws Exception
     */
    @GetMapping("/followList")
    public Result getFollowList(Integer userid) throws Exception {
        //先查询当前用户的所有粉丝id列表
        LambdaQueryWrapper<Friendship> wrapper = new LambdaQueryWrapper<Friendship>()
                .eq(Friendship::getUserId, userid)
                .select(Friendship::getFriendId);
        // 2. 使用 selectObjs 查询，直接返回 friendId 列表（Object类型，需强转）
        List<Object> friendIdObjs = friendshipMapper.selectObjs(wrapper);

        // 3. 转换为 Integer 列表（避免类型转换异常）
        List<Integer> ids = friendIdObjs.stream()
                .map(obj -> (Integer) obj) // 强转 Integer
                .toList();

        log.info("查出来的好友id ：{}", ids);

        List<User> list = new ArrayList<>();
        //查询好友的基本信息
        for (int id : ids) {
            //先在user表中查name和avatar
            User u = userMapper.selectById(id);
            if (u == null) return Result.success("查询出错");
            list.add(u);
        }
        return Result.success(list);
    }

    /**
     * 获取userId用户的好友列表
     *
     * @param
     * @return
     * @throws Exception
     */
    @GetMapping("/friendList")
    public Result getFriendList(Integer userid) throws Exception {
        //先查询当前用户的所有朋友id列表
        LambdaQueryWrapper<Friendship> wrapper = new LambdaQueryWrapper<Friendship>()
                .eq(Friendship::getUserId, userid).eq(Friendship::getStatus, "accepted")
                .select(Friendship::getFriendId);
        // 2. 使用 selectObjs 查询，直接返回 friendId 列表（Object类型，需强转）
        List<Object> friendIdObjs = friendshipMapper.selectObjs(wrapper);

        // 3. 转换为 Integer 列表（避免类型转换异常）
        List<Integer> ids = friendIdObjs.stream()
                .map(obj -> (Integer) obj) // 强转 Integer
                .toList();

        log.info("查出来的好友id ：{}", ids);

        List<FriendShipVO> list = new ArrayList<>();
        //查询好友的基本信息
        for (int id : ids) {
            if (friendShipService.count(
                    new LambdaQueryWrapper<Friendship>().eq(Friendship::getUserId, id)
                            .eq(Friendship::getFriendId, userid).eq(Friendship::getStatus, "accepted")
            ) != 1) continue;//不是双向好友

            //先在user表中查name和avatar
            User u = userMapper.selectById(id);
            if (u == null) return Result.success("查询出错");

            //再查最近的一条聊天记录 (userId,id)之间的最近一条
            WsChatMessage latestMessage = getLatestMessage(userid, id);
            FriendShipVO dto = FriendShipVO.builder()
                    .id(id)
                    .name(u.getUsername())
                    .avatar(u.getAvatar())
                    .content(latestMessage == null ? "没有最近聊天记录" : latestMessage.getContent())
                    .time(latestMessage == null ? LocalTime.of(0, 0, 0) : latestMessage.getSendTime().toLocalTime())
                    .build();
            list.add(dto);
        }

        return Result.success(list);
    }

    private WsChatMessage getLatestMessage(Integer user1, Integer user2) {
        LambdaQueryWrapper<WsChatMessage> wrapper = new LambdaQueryWrapper<WsChatMessage>()
                // 1. 先加一个and条件块，这个块里两个条件：sender=user1 且 receiver=user2
                .and(w -> w.eq(WsChatMessage::getSender, user1)
                        .eq(WsChatMessage::getReceiver, user2))

                // 2. 或者满足下面的条件块：sender=user2 且 receiver=user1
                .or(w -> w.eq(WsChatMessage::getSender, user2)
                        .eq(WsChatMessage::getReceiver, user1))

                // 3. 最后按 sendTime 逆序吧
                .orderByDesc(WsChatMessage::getSendTime)
                .last("LIMIT 1");//只查一条熬

        return wschatMessageMapper.selectOne(wrapper);
    }

}
